package com.byedu.controller;

import com.alibaba.fastjson.JSONObject;
import com.byedu.entity.ApiUserInfo;
import com.byedu.entity.PayBean;
import com.byedu.entity.WeiXinUserInfo;
import com.byedu.service.PayBeanService;
import com.byedu.utils.CommonUtil;
import com.byedu.utils.RectUrl;
import com.byedu.utils.TenpayUtil;
import com.byedu.utils.http.HttpRequestUtil;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Controller
public class LoginController {
    @Resource
    private PayBeanService payBeanService;
    private static Logger logger = Logger.getLogger(LoginController.class);


    @RequestMapping(value = "/error")
    public void error(HttpServletRequest request,
                      final HttpServletResponse response) throws IOException, ServletException {
        //设置缓存时间为1小时:时间单位为毫秒
        response.setDateHeader("Expires", System.currentTimeMillis() + 1000 * 3600);
        String data = "abcdefghigk";
        response.getOutputStream().write(data.getBytes());
    }


    @RequestMapping(value = "/index")
    public void index(HttpServletRequest request,
                      final HttpServletResponse response) throws IOException {

        PayBean checkPayBean = payBeanService.selectPayBeanId("wx76923c18571682c81495510814");
        logger.info(checkPayBean.toString());
        JSONObject jsonAdd = new JSONObject();
        jsonAdd.put("userId", "8e2659e4c3064a45b9bb10d9d7bf9c27");
        jsonAdd.put("courseId", checkPayBean.getCourse_id());
        jsonAdd.put("purchaseTime", "12133223");
        jsonAdd.put("orderId", "wx76923c18571682c81495510814");

        String addString = HttpRequestUtil.sendPost(RectUrl.ADDUSERURL, jsonAdd);// 拿去返回值

    }

    @RequestMapping("/tologin")

    public void tologin(HttpServletRequest request,
                        final HttpServletResponse response) throws IOException {

        String gotoURL = request.getParameter("gotoURL");
        if (gotoURL != null)
            response.sendRedirect(gotoURL);
    }


    @RequestMapping("/loginServlet")
    public void loginServlet(HttpServletRequest request,
                             final HttpServletResponse response) throws IOException {
        logger.info("....loginServlet....");
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        response.setCharacterEncoding("utf-8");

        String openid = request.getParameter("openid");
        String url = null;

        //修改用户昵称，地址
//        if (openid == null) {
            /**
             * 第一步：用户同意授权，获取code:https://open.weixin.qq.com/connect/oauth2/authorize
             * ?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE
             * &state=STATE#wechat_redirect
             */
            url = TenpayUtil.getRedirect_userinfourl(
             RectUrl.AUTHORIZEURLRELOGIN);// 授权后重定向的回调链接地址，请使用urlencode对链接进行处理（文档要求）
            // 按照文档要求拼接访问地址
            response.sendRedirect(url);// 跳转到要访问的地址

//        } else {
//
//            //有openId的不再认证了
//            ApiUserInfo apiUserInfo = null;
//            JSONObject jsonPara = new JSONObject();
//            jsonPara.put("openId", openid);
//            apiUserInfo = RectUrl.getApiUserInfo(jsonPara);
//            response.sendRedirect(RectUrl.sendRedirect(apiUserInfo));
//        }


    }

    @RequestMapping("/mainServlet")
    public void mainServlet(HttpServletRequest request,
                            final HttpServletResponse response) throws IOException, ServletException {
        ApiUserInfo apiUserInfo = null;
        try {
//		String appid = "";//公众号appid
//		String appsecret = "";//公众号秘钥
            //微信返回的code
            String code = request.getParameter("code");

            //获取openId和access_token（获取openId后调用统一支付接口https://api.mch.weixin.qq.com/pay/unifiedorder）

            JSONObject jsonObject = CommonUtil.httpsRequest(TenpayUtil.getAccess_tokenUrl(code), "GET", null);

            String openId = null;

            if (null != jsonObject) {
                int expiresIn = jsonObject.getIntValue("expires_in");
                openId = jsonObject.getString("openid");

                JSONObject jsonPara = new JSONObject();
                jsonPara.put("openId", openId);
                apiUserInfo = RectUrl.getApiUserInfo(jsonPara);
                logger.error(apiUserInfo.toString());

                if (apiUserInfo == null) {
                    request.setAttribute("ErrorMsg", "api服务器访问失败");
                    request.getRequestDispatcher("shop/error.jsp").forward(request, response);

                }
                //如果是新用户
                if (apiUserInfo.isNewFlag()) {
                    response.sendRedirect(RectUrl.AUTHORIZEURLLogin + "?openid=" + openId);
                    return;
                }
                if (expiresIn < 10) {
                    /**
                     * 第三步：刷新access_token（如果需要）
                     */
                    JSONObject jsonObject2 = CommonUtil.httpsRequest(TenpayUtil.getRefreshUrl(jsonObject.getString("refresh_token")), "GET", null);// 拿去返回值
                }
            }

            response.sendRedirect(RectUrl.sendRedirect(apiUserInfo));
        } catch (Exception ex) {
            ex.printStackTrace();
            request.setAttribute("ErrorMsg", "老用户登陆报错" + ex.getMessage());
            request.getRequestDispatcher("shop/error.jsp").forward(request, response);
        }
    }


    @RequestMapping("/reloginServlet")
    public void reloginServlet(HttpServletRequest request,
                               final HttpServletResponse response) throws IOException, ServletException {
        logger.info("****reloginServlet****");
        ApiUserInfo apiUserInfo = null;
        try {
            //微信返回的code
            String code = request.getParameter("code");

            //获取openId和access_token（获取openId后调用统一支付接口https://api.mch.weixin.qq.com/pay/unifiedorder）
            String openId = "";
            String access_token = "";
            JSONObject jsonObject = CommonUtil.httpsRequest(TenpayUtil.getAccess_tokenUrl(code), "GET", null);

            if (null != jsonObject) {
                int expiresIn = jsonObject.getIntValue("expires_in");
                openId = jsonObject.getString("openid");
                //此处判断
                access_token = jsonObject.getString("access_token");
                if (expiresIn < 10) {
                    /**
                     * 第三步：刷新access_token（如果需要）
                     */
                    JSONObject jsonObject2 = CommonUtil.httpsRequest(TenpayUtil.getRefreshUrl(jsonObject.getString("refresh_token")), "GET", null);// 拿去返回值
                    access_token = jsonObject2.getString("access_token");
                }
            }

            String json3 = HttpRequestUtil.httpRequest(TenpayUtil.getUserInfoUrl(access_token, openId));// 拿去返回值
            logger.error(json3);

            WeiXinUserInfo userInfo = JSONObject.parseObject(json3, WeiXinUserInfo.class);
            //存储用户信息,返回user

            logger.info(userInfo.toString());
            JSONObject jsonPara = new JSONObject();

            jsonPara.put("openId", userInfo.getOpenid());
            jsonPara.put("nickname", userInfo.getNickname());
            jsonPara.put("sex", userInfo.getSex());
            jsonPara.put("headImgUrl", userInfo.getHeadimgurl());
            jsonPara.put("province", userInfo.getProvince());
            jsonPara.put("city", userInfo.getCity());
            jsonPara.put("country", userInfo.getCountry());

            apiUserInfo = RectUrl.getApiUserInfo(jsonPara);

            if (apiUserInfo == null) {
                request.setAttribute("ErrorMsg", "API服务器无法访问");
                request.getRequestDispatcher("shop/error.jsp").forward(request, response);
                return;
            }
            response.sendRedirect(RectUrl.sendRedirect(apiUserInfo));

        } catch (Exception ex) {
            ex.printStackTrace();
            request.setAttribute("ErrorMsg", "新用户登陆接口报错" + ex.getMessage());
            request.getRequestDispatcher("shop/error.jsp").forward(request, response);
        }
    }
}
